import React, { useState } from 'react'
import {
    View,
    Text,
    ImageBackground,
    StyleSheet,
    Image,
    TouchableOpacity,
    ScrollView,
    TextInput
} from 'react-native'
import '../../common/global'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons'
import { AsyncStorage } from 'react-native';
import {
    useFocusEffect,
} from '@react-navigation/native';


const Comments = ({ navigation, route }) => {
    //获得传来的动态id
    let dongId = route.params.id;
    const [value, onChangeText] = React.useState('');
    const [list, setList] = useState([]);
    let helpList = [];

    //存储全局数组
    const setQUanList = async (list) => {
        let data = JSON.stringify(list);
        await AsyncStorage.setItem(
            'quanList', data
        );
    }

    //拿取全局数组
    const getQUanList = async () => {
        let data = await AsyncStorage.getItem('quanList');
        data = JSON.parse(data);
        return data;
    }

    //设置评论增加标记
    const setAdd1 = async () => {
        let data = JSON.stringify(false);
        await AsyncStorage.setItem(
            'addNew', data
        );
    }
    const setAdd2 = async () => {
        let data = JSON.stringify(true);
        await AsyncStorage.setItem(
            'addNew', data
        );
    }
    //获取评论增加标记
    const getAdd = async () => {
        let data = await AsyncStorage.getItem('addNew');
        data = JSON.parse(data);
        return data;
    }
    //获取保存的评论数组
    const getData = async () => {
        let data = await AsyncStorage.getItem('dongComments');
        data = JSON.parse(data);
        return data;
    }
    //保存评论
    const saveData = async (data) => {
        console.log('保存的评论数据');
        console.log(data);
        data = JSON.stringify(data);
        await AsyncStorage.setItem(
            'dongComments', data
        );
    }
    //得到名字
    const getName = async () => {
        let data = await AsyncStorage.getItem('name');
        data = JSON.parse(data);
        return data;
    }

    useFocusEffect(
        React.useCallback(() => {
            async function open() {
                await setAdd1();
                await getData().then((res) => {
                    //判断是否为数组
                    if (res.__proto__.constructor == Array) {
                        return res;
                    } else {
                        return [];
                    }
                }).then((res) => {
                    if (res.length == 0) {
                        return;
                    } else {
                        //获得该动态下的数组
                        helpList = [...res];
                        
                        let newList = res.filter((v) => {
                            if (v.id == dongId) {
                                return true;
                            } else {
                                return false;
                            }
                        })
                       
                        if (newList.length == 0) {
                            return;
                        } else {
                            let newList2 = newList[0];
                            newList2 = newList2.list;
                            
                            setList(newList2);
                        }
                    }

                })
            }
            open();

            return () => {
                //如果评论发生了增加 就进行更新存储
                async function end() {
                    getAdd().then(async (res) => {
                        console.log(res,'是否执行更新');
                        if (res) {
                            await getData().then((res) => {
                                if (res != null) {
                                    return res;
                                } else {
                                    return [];
                                }
                            }).then(async (res) => {
                                console.log(res);
                                let newList = res.filter((v) => {
                                    if (v.id == dongId) {
                                        return true
                                    }
                                })
                                console.log(newList, '查看存储中是否已经有了数组');
                                //如果数组不为空
                                if (newList.length != 0) {
                                    let list1 = [...res];
                                    let index = list1.findIndex((v) => {
                                        return v.id == dongId;
                                    })
                                    await getQUanList().then( async (res) => {
                                        list1[index].list = res;
                                        console.log(list1[index].list,'执行修改的数组');
                                        await saveData(list1);
                                    })
                                    
                                } else {
                                    let list2 = [];
                                    let obj = {
                                        id: dongId,
                                        list: list
                                    }
                                    if (helpList.length == 0) {
                                        list2 = [obj];
                                    } else {
                                        list2 = [obj, ...helpList];
                                    }

                                    await saveData(list2);
                                }
                            })


                        };
                    })
                }
                end();
                navigation.navigate('pi');

            }
        }, []))

    const setTime = () => {
        var timestamp = Date.parse(new Date());
        var date = new Date(timestamp);
        var month = date.getMonth() + 1;
        var time = date.getFullYear() + '年' + month + '月' + date.getDate() + '日' + date.getHours() + ':' + date.getMinutes();
        return time;
    }
    //提交新的评论
    const setComments = async () => {
        if (!Boolean(value)) {
            return
        }
        let name = await getName();
        let time = setTime();
        let obj = {
            name,
            pic: require('../happy/img/111.jpg'),
            shenP: value,
            good: 0,
            isLike: false,
            time:time
        };
        list.unshift(obj);
        setList([...list]);
        await setQUanList(list);
        console.log(list,'提交状态下看到的全局变量');
    }

    return (
        <View style={{ flex: 1, backgroundColor: 'white', height: h, position: 'relative' }}>
            <ScrollView style={{ flex: 1, backgroundColor: 'white' }}>
                {
                    list.map((item, key) => {
                        return (
                            <View key={key} id={item.id} style={{ marginTop: 15, backgroundColor: 'white', borderBottomWidth: 1, borderColor: 'rgb(234,234,234)' }}>
                                <View style={styles.part1} >
                                    <Image style={styles.avatar} resizeMode="stretch" source={item.pic} />
                                    <Text id="name" style={styles.name}>{item.name}</Text>
                                </View>
                                <View style={styles.part2}>
                                    <Text id="article" style={styles.article}>{item.shenP}</Text>
                                </View>

                                <View style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-end' }}>
                                    
                                    <View style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginLeft: 14, marginRight: 20, marginBottom: 8 }}>
                                        <TouchableOpacity onPress={async () => {
                                            let help = [...list];
                                            help.forEach((v) => {
                                                if (v.time == item.time) {
                                                    if (v.isLike == true) {
                                                        v.good--;
                                                    } else {
                                                        v.good++;
                                                    }
                                                    v.isLike = !v.isLike;
                                                }
                                            })
                                            setList(help);
                                            await setAdd2(list);
                                            await setQUanList(help);
                                        }}>
                                            
                                            <Icon name={item.isLike ? 'arrow-up-thick' : 'arrow-up-bold-outline'} size={36} />
                                        </TouchableOpacity>

                                        <Text style={{ fontSize: 18, marginLeft: 6, color: 'black' }}>{item.good}</Text>
                                    </View>
                                </View>

                            </View>

                        )
                    })
                }
            </ScrollView>
            <View style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', position: 'absolute', bottom: 0, paddingBottom: 10, paddingTop: 10 }}>
                <TextInput
                    style={{ height: 40, flex: 8, backgroundColor: 'rgb(245,244,249)', marginLeft: 10, marginRight: 20, borderRadius: 10 }}
                    onChangeText={text => onChangeText(text)}
                    value={value}
                    placeholder='   说点什么吧'
                />
                <TouchableOpacity style={{ flex: 2 }} onPress={
                    async () => {
                        //点击提交的事件
                        onChangeText('');
                        await setAdd2();
                        setComments();
                    }
                }>
                    <Icon name='arrow-up-circle' size={36} style={{ color: 'green' }}></Icon>
                </TouchableOpacity>
            </View>
        </View>
    )
}
const styles = StyleSheet.create({
    container1: {
        flex: 1,
    },
    contentFindView: {
        height: 50,
        width: 50,
        position: 'absolute',
        left: 390,
        top: 650,
        opacity: 0.5
    },
    bestCom: {
        width: 80,
        backgroundColor: '#FF7A87',
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 20,
        paddingLeft: 3,
        marginBottom: 10
    },
    face: {
        color: '#FDE702'
    },
    container: {
        flex: 1,
        margin: 0,
        padding: 0,
        backgroundColor: '#eee',
    },
    part1: {
        paddingLeft: 20,
        paddingTop: 16,
        paddingBottom: 8,
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 10
    },
    part2: {
        paddingTop: 8,
        paddingLeft: 20,
        paddingBottom: 8,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#fff'
    },
    part3: {
        width: '90%',
        paddingLeft: 20,
        paddingTop: 8,
        paddingBottom: 8,
        flexDirection: 'row',
        flexWrap: 'wrap',
        justifyContent: 'center',
        backgroundColor: '#fff'
    },
    part4: {
        width: '90%',
        backgroundColor: '#F5F5F7',
        marginTop: 20,
        marginBottom: 20,
        padding: 10,
        // borderTopRightRadius:20,
        // borderTopLeftRadius:20,
        marginLeft: '5%',
        borderRadius: 10
    },
    part41: {
        // backgroundColor:'blue',
        flexDirection: 'row',
        alignItems: 'center',
    },
    part42: {
        // backgroundColor:'blue',
        flexDirection: 'row',
        alignItems: 'center',
    },
    part43: {
        width: '100%',
        flexDirection: 'row',
        flexWrap: 'wrap',
        paddingTop: 20,
        justifyContent: 'center'
    },
    arrowup: {
        color: '#3C94CD',
        marginLeft: 10
    },
    arrowdown: {
        color: '#3C94CD',
        marginLeft: 6
    },
    avatar: {
        // backgroundColor:'blue', 
        width: 40,
        height: 40,
        borderRadius: 200
    },
    name: {
        marginLeft: ptd(12),
        fontSize: 19,
        color: '#5A5B5F'
    },
    article: {
        fontSize: 20,
        width: '95%'
    },
    article1: {
        fontSize: 18,
        width: '100%'
    },
    conImg: {
        //backgroundColor:'yellow',
        width: 145,
        height: 145,
        borderRadius: 8,
        marginRight: 6,
        marginBottom: 3,
        borderColor: '#ddd',
        borderWidth: 1
    },
    txtBox: {
        width: '100%',
        height: 40,
        marginBottom: 5,
        backgroundColor: '#F5F5F7',
        flexDirection: 'row'
    },
    txtInput: {
        width: '85%',
        backgroundColor: '#fff',
        borderRadius: 20,
        marginLeft: 5,
    },
    txtBtn: {
        width: 45,
        height: 30,
        backgroundColor: 'skyblue',
        marginTop: 5,
        marginLeft: 5,
        borderRadius: 10,
    },
    btnTxt: {
        textAlign: "center",
        lineHeight: 30,
        color: '#fff',
        fontSize: 18
    }
})

export default Comments
